package com.timi_licai.timi_licai_account;

import android.animation.ValueAnimator;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.timi_licai.timi_licai_account.adapter.AddAdapter;
import com.timi_licai.timi_licai_account.adapter.ShowCategoryAdapter;
import com.timi_licai.timi_licai_account.database.DatabaseUtils;
import com.timi_licai.timi_licai_account.dialog.CameraDialog;
import com.timi_licai.timi_licai_account.listener.CameraDialogInterface;
import com.timi_licai.timi_licai_account.listener.EditDialogInterface;
import com.timi_licai.timi_licai_account.dialog.EditDialog;
import com.timi_licai.timi_licai_account.model.ShowCategory;
import com.timi_licai.timi_licai_account.utils.DatabaseQueryUtils;
import com.timi_licai.timi_licai_account.utils.DateUtils;
import com.timi_licai.timi_licai_account.utils.KeyLineUtils;

import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;


public class AddActivity extends ActionBarActivity implements View.OnClickListener, AbsListView.OnScrollListener, AdapterView.OnItemClickListener, EditDialogInterface, CameraDialogInterface {
    private GridView numGrid;
    private GridView showCategoryGrid;
    private ShowCategoryAdapter adapter;
    private LinearLayout showLayout;
    private ImageView editButton;
    private Dialog dialog;
    private ImageView calButton;//显示日历的button
    private ImageView camButton;//显示照相机的button
    private TextView showTxtNum;//用来显示输入的数值
    private List<String> list;//保存计算机中键盘的值
    private StringBuilder sb;//用来保存计算器输入的值
    private String dbDate = "";//保存插入数据库的日期
    private boolean flag = false;
    private String dialogInputContent;//保存用户输入的备忘记录
    private ContentValues values;//存放插入数据库数据的实体类

    private ImageView btnBack;
    private List<ShowCategory> categoryList;//存放从数据库中取出的分类信息
    private TextView txtCategoryChoose;//选中的分类的名称
    private int consumeTypeId = 1;
    private int ioChoose = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        numGrid = (GridView) findViewById(R.id.grid_num);
        showLayout = (LinearLayout) findViewById(R.id.showLayout);
        showCategoryGrid = (GridView) findViewById(R.id.grid_show_category);
        calButton = (ImageView) findViewById(R.id.calendar);
        editButton = (ImageView) findViewById(R.id.edit);
        showTxtNum = (TextView) findViewById(R.id.txt_show_num);
        camButton = (ImageView) findViewById(R.id.camera);
        btnBack = (ImageView) findViewById(R.id.btn_back);
        txtCategoryChoose = (TextView) findViewById(R.id.add_activity_show_category_txt);

        sb = new StringBuilder();
        values = new ContentValues();
        showLayout.setOnClickListener(this);
        calButton.setOnClickListener(this);
        editButton.setOnClickListener(this);
        camButton.setOnClickListener(this);
        btnBack.setOnClickListener(this);

        //将计算器的值加入List中
        list = KeyLineUtils.addDataToList();
        AddAdapter addAdapter = new AddAdapter(this, list);
        //为数字键盘设置Adapter
        numGrid.setAdapter(addAdapter);

        //设置显示类别的Adapter的数据
        categoryList = getShowCategoryListFromDB();

        //设置显示分类信息GridView的Adapter
        adapter = new ShowCategoryAdapter(this, categoryList);
        showCategoryGrid.setAdapter(adapter);
        showCategoryGrid.setOnScrollListener(this);
        showCategoryGrid.setOnItemClickListener(this);
        numGrid.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        List<ShowCategory> listFromDB = getShowCategoryListFromDB();
        categoryList.clear();
        categoryList.addAll(listFromDB);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.edit:
                //todo 弹出  记录日志的dialog
                dialog = new EditDialog(this, R.style.editDialog, this);
                dialog.setContentView(R.layout.dialog_discription);
                dialog.show();
                break;
            case R.id.showLayout:
                if (flag) {
                    hideCal();
                } else {
                    showCal();
                }
                break;
            case R.id.calendar:
                //todo 弹出日历dialog
                Intent intent = new Intent(this, CalendarActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.camera:
                //todo 弹出相机dialog
                dialog = new CameraDialog(this, R.style.cameraDialog, this);
                View view = LayoutInflater.from(this).inflate(R.layout.dialog_camera, null);
                dialog.setContentView(view,
                        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT));
                Window window = dialog.getWindow();
                window.setGravity(Gravity.BOTTOM);
                window.setWindowAnimations(R.style.cameraDialogAnim);
                WindowManager.LayoutParams layoutParams = window.getAttributes();
                layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
                layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                dialog.onWindowAttributesChanged(layoutParams);
                dialog.show();
                break;
            case R.id.btn_back:
                this.finish();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 200) {
            dbDate = data.getStringExtra("dbDate");
        }
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (view.getTag().equals("categoryGridView")) {
            if (position == categoryList.size() - 1) {
                //todo  跳转到添加页面
                Intent intent = new Intent(this, AddCategoryActivity.class);
                startActivity(intent);

            } else if (position == 0) {
                txtCategoryChoose.setText("收入");
                ioChoose = 1;

            } else {
                txtCategoryChoose.setText(categoryList.get(position).getTypeName());
                consumeTypeId = categoryList.get(position).getId();
            }
        } else if (view.getTag().equals("numGirdView")) {
            switch (position) {
                case 11:
                    if (dbDate.equals("")) {
                        dbDate = DateUtils.formatDateForDatabase(Calendar.getInstance().getTime());
                    }
                    //将数据库中的每个账本交易数量取出 加 1 然后放回去
                    int bookid = DatabaseQueryUtils.getSelectedAccountBook();
                    Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_ACCOUNT_BOOK,
                            new String[]{"bookcount"}, "_id=?", new String[]{bookid + ""}, null);
                    values.put("bookid", bookid);
                    int bookcount = 0;
                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            bookcount = cursor.getInt(cursor.getColumnIndex("bookcount"));
                        }
                    }
                    bookcount++;
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("bookcount", bookcount);
                    DatabaseUtils.update(MyConstants.TABLE_ACCOUNT_BOOK,
                            contentValues, "_id=?", new String[]{bookid + ""});
                    values.put("type_id", consumeTypeId);
                    values.put("io_choose", ioChoose);
                    values.put("fee", sb.toString());
                    values.put("photo_path", "null");
                    values.put("createtime", dbDate);
                    insertContent(values);
                    break;
                case 9:
                    //todo  点击了AC键
                    sb = new StringBuilder();
                    break;
                case 10:
                    sb.append("0");
                    break;
                default:
                    String clickString = list.get(position);
                    int clickNum = Integer.parseInt(clickString);
                    sb.append(clickNum + "");
            }
            if (sb != null) {
                showTxtNum.setText(sb.toString());
            } else {
                showTxtNum.setText("0");
            }

        }
    }

    /**
     * 编辑按钮的点击dialog的回调方法
     *
     * @param id
     */
    @Override
    public void editDialogClick(int id) {
        switch (id) {
            case R.id.dialog_cancel:
                dialog.cancel();
                values.put("description", "没有插入备注");
                break;

            case R.id.dialog_confirm:
                if (TextUtils.isEmpty(dialogInputContent)) {
                    values.put("description", "没有插入备注");
                } else {
                    values.put("description", dialogInputContent);
                }
                dialog.cancel();
                break;
        }
    }

    /**
     * 添加备忘的Dialog回传输入值的方法
     *
     * @param str
     */
    @Override
    public void editDialogInputContent(String str) {
        dialogInputContent = str;
    }

    private void insertContent(ContentValues values) {
        boolean insert = DatabaseUtils.insert(MyConstants.TABLE_ACCOUNT_BOOK_DETAILS, values);
        if (true) {
            this.finish();
        }
    }

    private void showCal() {
        final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.showLayout));
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        ValueAnimator animator = ValueAnimator.ofInt(-500, 0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int cur = (Integer) animation.getAnimatedValue();
                params.bottomMargin = cur;
                showLayout.setLayoutParams(params);
            }
        });
        animator.setDuration(300);
        animator.start();
        flag = true;
    }

    private void hideCal() {
        final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                getResources().getDimensionPixelSize(R.dimen.align_top));
        params.addRule(RelativeLayout.BELOW, R.id.view_flag);
        ValueAnimator animator = ValueAnimator.ofInt(0, 500);
        params.setMargins(0, getResources().getDimensionPixelSize(R.dimen.align_top), 0, 0);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int cur = (Integer) animation.getAnimatedValue();
                params.bottomMargin = cur;
                showLayout.setLayoutParams(params);
            }
        });
        animator.setDuration(300);
        animator.start();
        flag = false;
    }

    /**
     * 点击相机dialog的回调方法
     *
     * @param id
     */
    @Override
    public void getCameraDialogClick(int id) {
        switch (id) {
            case R.id.dialog_camera_from_book:
                //从本地图片库取图片
                break;
            case R.id.dialog_camera_take_photo:
                //打开相机
                Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                //   startActivityForResult(openCameraIntent);
                break;

            case R.id.dialog_cancel:
                //取消
                dialog.cancel();
                break;

        }

    }

    /**
     * 从数据库中查出表中所有的分类的类别信息
     *
     * @return
     */
    private List<ShowCategory> getShowCategoryListFromDB() {
        List<ShowCategory> categoryList = new LinkedList<>();
        ShowCategory category = new ShowCategory();
        category.setTypePath("添加的图片的路径");
        category.setTypeName("收入");
        categoryList.add(category);
//        Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_CONSUME_TYPE, null, null, null, null);
        Cursor cursor = DatabaseUtils.query(MyConstants.TABLE_CONSUME_TYPE, null, "ismark=?", new String[]{0 + ""}, null);
        ShowCategory showCategory;
        if (cursor != null) {
            while (cursor.moveToNext()) {
                showCategory = new ShowCategory();
                String typename = cursor.getString(cursor.getColumnIndex("typename"));
                String typepath = cursor.getString(cursor.getColumnIndex("typepath"));
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                showCategory.setTypeName(typename);
                showCategory.setTypePath(typepath);
                showCategory.setId(id);
                categoryList.add(showCategory);
            }
        }
        category = new ShowCategory();
        category.setTypePath("添加的图片的路径");
        category.setTypeName("添加分类");
        categoryList.add(category);
        return categoryList;
    }
}
